package com.woniuxy.qimengorder.service.impl;

import com.woniuxy.qimengorder.bean.OrderBean;
import com.woniuxy.qimengorder.mapper.OrderMapper;
import com.woniuxy.qimengorder.service.OrderService;

import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2020-08-25 20:10:25
 */
@Transactional(readOnly = true)
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ValueOperations valueOperations;
    private HttpServletRequest servletRequest;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OrderBean queryById(String id) {
        return this.orderMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<OrderBean> queryAllByLimit(int offset, int limit) {
        return this.orderMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    public void insert(OrderBean order) {
        //生成订单编号
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = df.format(date);
        int nums = (int) (Math.random() * 9999) + 1;// 随机数
        String orderno = "WN" + time + nums;

        order.setNumber(orderno);
        //获取下单时间
        order.setOrderTime(date);

        //获取下单家长的信息
        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtaWNyb3NlcnZlci1zdHVkeSIsImF1ZCI6Im1hcHAiLCJyZWZyZXNoQXQiOjE1OTg0MzYyMzMsImlzcyI6Indvbml1IiwiZXhwIjoxNTk4NDM4MDMzLCJ1c2VyTmFtZSI6ImRlbW9EYXRhIiwiaWF0IjoxNTk4NDM0NDMzfQ.wL-vjK3KuLQAY3nCahLyOGorzEsHNO7oWeUEJTnbNmk";//servletRequest.getHeader("token");
        Map<String, Object> data = (Map<String, Object>)valueOperations.get(token);
        System.out.println("家长的信息:"+data);


        orderMapper.insert(order);
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    public OrderBean update(OrderBean order) {
        this.orderMapper.update(order);
        return this.queryById(order.getNumber());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.orderMapper.deleteById(id) > 0;
    }
}